<script lang="ts">
import {defineComponent, ref, PropType, computed, watch} from 'vue'

/**
 * 栏目搜索
 */
export default defineComponent({
  name: "ColumnSelectSearch",
  emits: ['update:modelValue', 'change', 'input'],
  props: {
    modelValue: Object as PropType<{ [key: string]: any }>,
    column: {
      type: Array as PropType<Array<{ key: string, name: string }>>,
      required: true
    }
  },
  setup(props, context) {
    let newAttrs = {...context.attrs}
    delete newAttrs['onUpdate:modelValue']

    /**
     * 搜索字段
     */
    const find = ref(props.column[0].key)

    /**
     * 搜索关键词
     */
    const keyword = ref('')


    /**
     * 选择框宽度
     */
    const selectLabel = computed(() => {
      if (find.value) {
        for (let i = 0; i < props.column.length; i++) {
          if (props.column[i].key === find.value) {
            return props.column[i].name
          }
        }
      } else {
        return props.column[0].name
      }
      return '请选择'
    })


    /**
     * 选择框宽度
     */
    const keys = computed(() => {
      let keys = [];
      props.column.forEach(item => {
        keys.push(item.key)
      })
      return keys
    })


    /**
     * 监控数据变化
     */
    watch([find, keyword], (newValue) => {
      let where = {}
      for (let key in props.modelValue) {
        if (keys.value.indexOf(key) === -1) {//
          where[key] = props.modelValue?.[key]
        }
      }
      where[find.value] = keyword.value
      context.emit('update:modelValue', where)
      context.emit('change', where)
      context.emit('input', where)
    }, {
      deep: true,
      immediate: true
    })


    return {
      find,
      keyword,
      newAttrs,
      selectLabel
    }
  }
})
</script>

<template>
  <el-input class="column-select-search" v-bind="newAttrs" v-model.trim="keyword">
    <template #prepend>
      <el-dropdown>
        <span class="app-tap">
          {{ selectLabel }}
          <app-icon name="ArrowDown"/>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item v-for="(item,index) in column" :key="index" @click.native="find=item.key">
              {{ item.name }}
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </template>
  </el-input>
</template>
<style lang="scss" scoped>
.column-select-search {
  width: 100%;

  :deep(.el-input-group__prepend) {
    padding-right: 15px;
    padding-left: 20px;
  }
}
</style>